package com.sywb.chuangyebao.contract;

import android.Manifest;
import android.os.CountDownTimer;
import android.text.TextUtils;

import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.bean.InterestIndustryInfo;
import com.sywb.chuangyebao.bean.UserInfo;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;

import org.bining.footstone.db.DbManager;
import org.bining.footstone.log.Logger;
import org.bining.footstone.mvp.IView;
import org.bining.footstone.presenter.PermissionsPresenter;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.utils.SharedUtils;

import java.util.List;

/**
 * 获取Token的Presenter
 */
public interface BaseTokenContract {

    interface View extends IView {

        /**
         * 判断账号是否已注册后，根据获取的状态设置界面显示
         *
         * @param isRegister 是否已注册
         */
        void resultIsRegister(boolean isRegister, String message);

        /**
         * 设置获取验证码按钮的显示样式和是否可点击
         *
         * @param text
         * @param isClick
         */
        void setVerificationState(String text, boolean isClick);
    }

    abstract class Presenter<T extends View> extends PermissionsPresenter<T> {

        private CountDownTimer mCountDownTimer;

        private HttpCallback<UserInfo> tokenCallback;

        @Override
        public void onStart() {
            questPermissions(new String[]{Manifest.permission.READ_PHONE_STATE});
        }

        @Override
        public void onPermissionsSuccess(String[] strings) {
        }

        @Override
        public void onPermissionsFailure(String strMsg) {
            super.onPermissionsFailure(strMsg);
        }

        public void ssoExists(String mobile) {
            HttpUtils.ssoExists(mobile, new HttpCallback<Boolean>() {
                @Override
                public void onSuccess(Boolean b) {
                    if (mView != null) {
                        mView.resultIsRegister(b, b ? "该手机号已注册,请直接登录" : "该手机号还未注册,请先注册");
                    }
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    if (mView != null) {
                        mView.resultIsRegister(false, strMsg);
                    }
                }
            });
        }

        public void sendCode(String mobile) {
            HttpUtils.sendCaptcha(mobile, new HttpCallback<String>() {
                @Override
                public void onStart() {
                    super.onStart();
                    if (mCountDownTimer == null) {
                        mCountDownTimer = new CountDownTimer(60000, 1000) {
                            @Override
                            public void onTick(long millisUntilFinished) {
                                String tip = "重新发送(";
                                if (millisUntilFinished / 1000 < 10) {
                                    tip += "0" + millisUntilFinished / 1000 + ")";
                                } else {
                                    tip += millisUntilFinished / 1000 + ")";
                                }
                                if (mView != null) {
                                    mView.setVerificationState(tip, false);
                                }
                            }

                            @Override
                            public void onFinish() {
                                if (mView != null) {
                                    mView.setVerificationState(null, true);
                                }
                            }
                        };
                    }
                    mView.setVerificationState("正在发送中", false);
                }

                @Override
                public void onSuccess(String s) {
                    mCountDownTimer.start();
//                    showMessage("验证码：" + s);
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    mCountDownTimer.onFinish();
                }
            });
        }

        public HttpCallback<UserInfo> getTokenCallback() {
            if (tokenCallback == null) {
                tokenCallback = new HttpCallback<UserInfo>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        onStartAsync();
                    }

                    @Override
                    public void onSuccess(UserInfo userInfo) {
                        SharedUtils.put(Constants.USEROPENID, userInfo.uid);
                        SharedUtils.put(Constants.USERREFRESHTOKEN, userInfo.refresh_token);
                        SharedUtils.put(Constants.USERACCESSTOKEN, userInfo.access_token);
                        SharedUtils.put(Constants.USERAUTHTOKEN, userInfo.token);
                        SharedUtils.put(Constants.USERAUTHTOKENSIG, userInfo.token_sig);
                        SharedUtils.put(Constants.HTTP_SSO_BIND, userInfo.mobile);

                        DbManager.getInstance().save(userInfo);

                        PushServiceFactory.getCloudPushService().checkPushChannelStatus(new CommonCallback() {
                            @Override
                            public void onSuccess(String s) {
                                Logger.e("checkPushChannelStatus：" + s);
                                if (s.equals("on")) {
                                    String openId = SharedUtils.getString(Constants.USEROPENID);
                                    if (!TextUtils.isEmpty(openId)) {
                                        PushServiceFactory.getCloudPushService().bindAccount(openId, new CommonCallback() {
                                            @Override
                                            public void onSuccess(String s) {
                                                Logger.e("阿里云推送绑定账号成功");
                                            }

                                            @Override
                                            public void onFailed(String s, String s1) {
                                                Logger.e("阿里云推送绑定账号失败");
                                            }
                                        });
                                    }
                                }
                            }

                            @Override
                            public void onFailed(String s, String s1) {
                            }
                        });

                        if (SharedUtils.getString(Constants.USEROPENID, null) != null) {
                            clearGoodatUpdate();
                        }

                        SharedUtils.put(Constants.USERMOBILEVERIFY, userInfo.mobile_verify == 1);
                        SharedUtils.put(Constants.USERISLOGIN, true);

                        afterLogin(userInfo);

                        RxBus.get().post(Constants.USERISLOGIN, "true");
                    }

                    @Override
                    public void onError(String strMsg) {
                        super.onError(strMsg);
                        onErrorAsync(strMsg);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        onFinishAsync();
                    }
                };
            }
            return tokenCallback;
        }

        public void clearGoodatUpdate() {
            SharedUtils.put(Constants.USERBUSINESSPERIOD, 0);
            List<InterestIndustryInfo> list = DbManager.getInstance().query(InterestIndustryInfo.class);
            for (InterestIndustryInfo info : list) {
                if (info.isChecked) {
                    info.isChecked = false;
                }
            }
            DbManager.getInstance().save(list);
        }

        protected void afterLogin(UserInfo mobile) {

        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            if (mCountDownTimer != null) {
                mCountDownTimer.cancel();
            }
        }
    }
}
